import _ from 'lodash'
const tiandituToken = '96636075e679831995fb3d80b02e555a'
const vecUrl = 'http://t0.tianditu.com/vec_w/wmts?tk=' + tiandituToken // 矢量
const cvaUrl = 'http://t0.tianditu.com/cva_w/wmts?tk=' + tiandituToken

export const vecBaseMapStyle = {
  version: 8,
  sources: {
    'raster-vec': {
      type: 'raster',
      tiles: [
        vecUrl +
          '&service=WMTS&version=1.0.0&request=GetTile&layer=vec&style=default&format=tiles&TileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}',
      ],
      tileSize: 256,
    },
    'raster-cva': {
      type: 'raster',
      tiles: [
        cvaUrl +
          '&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles',
      ],
      tileSize: 256,
    },
  },
  layers: [
    {
      id: 'vec-tiles',
      type: 'raster',
      source: 'raster-vec',
    },
    {
      id: 'cva-tiles',
      type: 'raster',
      source: 'raster-cva',
    },
  ],
  glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
}

export const imgBaseMapStyle = {
  version: 8,
  sources: {
    'raster-img': {
      type: 'raster',
      tiles: [
        'https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' +
          tiandituToken,
      ],
      tileSize: 256,
    },
  },
  layers: [
    {
      id: 'img-tiles',
      type: 'raster',
      source: 'raster-img',
    },
  ],
  glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
}

class MapboxGLButtonControl {
  constructor({ className = '', title = '', eventHandler }) {
    this._className = className
    this._title = title
    this._eventHandler = eventHandler
  }

  onAdd(map) {
    this._map = map
    this._btn = document.createElement('button')
    this._btn.className = 'mapboxgl-ctrl-icon' + ' ' + this._className
    this._btn.type = 'button'
    this._btn.title = this._title
    this._btn.onclick = this._eventHandler

    this._container = document.createElement('div')
    this._container.className = 'mapboxgl-ctrl-group mapboxgl-ctrl'
    this._container.appendChild(this._btn)
    initBaseMapSwitcher(map)
    return this._container
  }

  onRemove() {
    this._container.parentNode.removeChild(this._container)
    this._map = undefined
  }
}
const basemapSwitchControl = new MapboxGLButtonControl({
  className: 'mapbox-gl-control-basemap',
  title: '切换底图',
  eventHandler: (event) => {
    const baseMapSwitchPanel = document.getElementById('basemap-switch-panel')
    if (baseMapSwitchPanel.style.bottom === '0px') {
      baseMapSwitchPanel.style.bottom = '-12rem'
    } else {
      baseMapSwitchPanel.style.bottom = '0px'
    }
  },
})

function initBaseMapSwitcher(map) {
  //监听底图切换
  // uniapp获取不到元素上的属性，只能每个单独绑定事件
  document
    .getElementById('vec-basemap-button')
    .addEventListener('click', (e) => {
      const target = e.target
      if (target.tagName === 'IMG') {
        toggleBaseMap('vec', map)
      }
    })

  document
    .getElementById('img-basemap-button')
    .addEventListener('click', (e) => {
      const target = e.target
      if (target.tagName === 'IMG') {
        toggleBaseMap('img', map)
      }
    })
}

function toggleBaseMap(type, map) {
  const imgMapButton = document.getElementById('img-basemap-button')
  const vecMapButton = document.getElementById('vec-basemap-button')

  if (type === 'vec') {
    switchMapStyle(vecBaseMapStyle, map)
    vecMapButton.classList.add('active')
    imgMapButton.classList.remove('active')
  } else if (type === 'img') {
    switchMapStyle(imgBaseMapStyle, map)
    imgMapButton.classList.add('active')
    vecMapButton.classList.remove('active')
  }
}

function switchMapStyle(style, map) {
  let newStyle = _.cloneDeep(style)
  const currentStyle = map.getStyle()
  const layers = currentStyle.layers.filter(
    (l) => l.id !== 'vec-tiles' && l.id !== 'cva-tiles' && l.id !== 'img-tiles'
  )
  const sources = currentStyle.sources
  newStyle.layers = [...newStyle.layers, ...layers] // 旧图层在上层
  newStyle.sources = { ...newStyle.sources, ...sources }
  map.setStyle(newStyle)
}

export default basemapSwitchControl
